'''LeNet in PyTorch.

1.Reference
---------
..[1]LeNet.
..[2]Original implementation: https://github.com/kuangliu/pytorch-cifar

2. 单通道(mnist)和3通道(cifar10)训练时构建模型需修改1个地方的参数:主类的self.conv1和self.fc1
   说明:知道修改self.fc1是报错+summary(train_net,(1,28,28))得出

'''
import torch.nn as nn
import torch.nn.functional as F

import torch

class LeNet(nn.Module):
    def __init__(self):
        super(LeNet, self).__init__()
        # self.conv1 = nn.Conv2d(3, 6, 5) # cifar10 图像输入
        self.conv1 = nn.Conv2d(1, 6, 5) # mnist 图像输入
        self.conv2 = nn.Conv2d(6, 16, 5)
        # self.fc1   = nn.Linear(16*5*5, 120) # cifar10图像输入
        self.fc1   = nn.Linear(16*4*4, 120)  # mnist 图像输入
        self.fc2   = nn.Linear(120, 84)
        self.fc3   = nn.Linear(84, 10)

    def forward(self, x):
        out = F.relu(self.conv1(x))
        out = F.max_pool2d(out, 2)
        out = F.relu(self.conv2(out))
        out = F.max_pool2d(out, 2) # 此处：cifar10时，out.shape==[2, 16, 5, 5],MNIST时，out.shape==[2, 16, 4, 4]
        out = out.view(out.size(0), -1)
        out = F.relu(self.fc1(out))
        out = F.relu(self.fc2(out))
        out = self.fc3(out)
        return out


def test(model, device, test_loader):
    model.eval()

    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            #test_loss += F.nll_loss(output, target, reduction='sum').item()  # sum up batch loss
            loss = F.cross_entropy(output, target)
            pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)

    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

def train(model, device, train_loader, optimizer, epoch):
    model.train()

    # lr = util.adjust_learning_rate(optimizer, epoch, args) # don't need it if we use Adam

    for batch_idx, (data, target) in enumerate(train_loader):
        '''
        MNIST:data.shape:[128,1,28,28],target.shape:[128]. 128 is batchSize defined before
        '''
        data, target = torch.tensor(data).to(device), torch.tensor(target).to(device)
        optimizer.zero_grad()
        output = model(data)
        # loss = F.nll_loss(output, target)
        loss = F.cross_entropy(output, target)
        loss.backward()
        optimizer.step()
        if batch_idx % 10 == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))
